﻿using System.ServiceModel;
using System.Collections.Generic;

namespace Web.Base
{
    internal static class WcfChannelFactory
    {
        private static readonly object SyncHelper = new object();
        private static readonly IDictionary<string, ChannelFactory> ChannelFactories = new Dictionary<string, ChannelFactory>(13);

        private static ChannelFactory<TChannel> GetChannelFactory<TChannel>(string endpointConfigurationName)
        {
            ChannelFactory<TChannel> channelFactory = null;
            if (ChannelFactories.ContainsKey(endpointConfigurationName))
            {
                channelFactory = ChannelFactories[endpointConfigurationName] as ChannelFactory<TChannel>;
            }
            if (null == channelFactory)
            {
                channelFactory = new ChannelFactory<TChannel>(endpointConfigurationName);

                lock (SyncHelper)
                {
                    ChannelFactories[endpointConfigurationName] = channelFactory;
                }
            }
            return channelFactory;
        }
        public static TChannel GetChannel<TChannel>(string endpointConfigurationName)
        {
            return GetChannelFactory<TChannel>(endpointConfigurationName).CreateChannel();
        }
    }
}